# -*- coding: UTF-8 -*-
# @Time : 2021-01-21 20:13
# @File : BasePage.py
import time

from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as ec
from utils.LogUtil import my_log
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from data.ExcelConfig import TestSteps, Elements, CaseData, TestCases
import allure
import datetime


# 1、定义类
class Action:
    def __init__(self, driver):
        self.driver = driver
        self.log = my_log('Base_Page')

    def xpath_click(self, **kwargs):
        by, value = kwargs["by"], kwargs["value"]
        if by == 'xpath':
            loc = MobileBy.XPATH, value
            WebDriverWait(self.driver, 20, 3).until(lambda x: x.find_element(by, value))
            ele = self.driver.find_element(*loc)
            ActionChains(self.driver).move_to_element(ele).click(ele).perform()
        else:
            self.log.error('定位类型错误')

    def xpath_send_keys(self, **kwargs):
        by, value, send = kwargs["by"], kwargs["value"], kwargs['send']
        if by == 'xpath':
            loc = MobileBy.XPATH, value
            WebDriverWait(self.driver, 20, 3).until(lambda x: x.find_element(MobileBy.XPATH, value))
            ele = self.driver.find_element(*loc)
            ActionChains(self.driver).move_to_element(ele).click(ele).send_keys(send).perform()
        else:
            self.log.error('定位类型错误')

    # 2、定义方法，xpath, id, click
    def by_xpath(self, value):
        """
        xpath 定位元素
        :param value:
        :return:
        """
        return self.by_find_element(By.XPATH, value)

    def by_id(self, value):
        """
        id 定位元素
        :param value:
        :return:
        """
        return self.by_find_element(By.ID, value)

    def send_keys(self, **kwargs):
        """
        通过定位元素发送内容
        :return:
        """
        by, value = kwargs['by'], kwargs['value']
        if by == 'id':
            loc = self.by_id(value)
        elif by == 'xpath':
            loc = self.by_xpath(value)
        loc.click()
        loc.send_keys(kwargs['send'])

    def by_find_element(self, by, value, timeout=30, poll_frequency=3, ):
        """
        显式等待,查找元素
        :param by:
        :param value:
        :param timeout:
        :param poll_frequency:
        :return:
        """
        try:
            WebDriverWait(self.driver, timeout, poll_frequency).until(lambda x: x.find_element(by, value))
            return self.driver.find_element(by, value)
        except Exception as e:
            self.log.error('没有找到元素:{}'.format(e))

    def is_toast_expect(self, **kwargs):
        """
        通过 by_find_element查找元素，类型By.XPATH ,toast_loc（value值）
        :return:
        """
        try:
            text = kwargs["expect"]
            toast_loc = "//*[contains(@text, '" + text + "')]"
            ele = WebDriverWait(self.driver, timeout=3, poll_frequency=1).until(
                lambda x: x.find_element(By.XPATH, toast_loc))
            self.log.info("获取toast内容为：{}".format(ele.text))
            return True
        except Exception as e:
            self.log.error("获取toast错误信息:{}".format(e))
            return False

    def click_btn(self, **kwargs):
        # 根据by类型，进行id，xpath方法调用
        by, value = kwargs["by"], kwargs["value"]
        if by == 'id':
            loc = self.by_id(value)
        elif by == 'xpath':
            loc = self.by_xpath(value)
        loc.click()

    def assert_toast_result(self, **kwargs):
        """
        错误拍图
        :param kwargs:
        :return:
        """
        toast_result = self.is_toast_expect(**kwargs)
        assert toast_result


"""
        try:
            assert toast_result == False
        except Exception as e:
            png = self.driver.get_screenshot_as_png()
            allure.attach(png, 'toast错误', allure.attachment_type.PNG)
            raise e
"""


def screenshot_allure(func):
    def get_err_screenshot(self, *args, **kwargs):
        try:
            func(self, *args, **kwargs)
        except Exception as e:
            png = self.driver.get_screenshot_as_png()
            name = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            allure.attach(png, name, allure.attachment_type.PNG)
            raise e

    return get_err_screenshot
